package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * @Discription: 保存发货状态同步回执
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/12/14 15:53
 */
@Slf4j
@Component
public class SavelogisticMsgService {

    /**
     * 保存发货状态同步回执
     *
     * @param jsonArray
     */
    public void saveLogisic(JSONArray jsonArray, String msgKey) {

        if (jsonArray == null) {
            log.error(" 发货回执消息体为空 " + msgKey);
            return;
        }

        // 当前系统时间
        Date sysDate = new Date(System.currentTimeMillis());
        // 修改数据为已同步
        String updateSql = "update T_OMS_OrderOutStorage set SYNCSTATUS = ? ,SYNCTIME = ? ,MSG = ? where id = ?";

        try {
            for (Object obj : jsonArray) {
                // 获取id
                JSONObject tempJsonObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                int id = tempJsonObj.getIntValue("ID");
                boolean issuccess = tempJsonObj.getBoolean("issuccess");

                if (issuccess) {
                    // 回传成功,修改状态
                    QueryEngine.getInstance().executeUpdate(updateSql, new Object[]{1, sysDate, "success", id});

                } else {
                    // 回传状态失败
                    String errcode = tempJsonObj.getString("error_code");
                    String errmsg = tempJsonObj.getString("error_msg");
                    QueryEngine.getInstance().executeUpdate(updateSql, new Object[]{2, sysDate, errmsg, id});

                }
            }
        } catch (Exception e) {

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            // 将错误以流写出
            e.printStackTrace(pw);
            log.error(pw.toString());

        }

    }
}

